package com.jiadeyu.controller;

import com.jiadeyu.mapper.UserMapper;
import com.jiadeyu.pojo.Result;
import com.jiadeyu.pojo.User;
import com.jiadeyu.service.UserService;
import com.jiadeyu.utils.JwtUtil;
import com.jiadeyu.utils.Md5Util;
import com.jiadeyu.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 用户相关
 */
@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final String registerRegexp = "^\\S{5,16}$";

    /**
     * 注册
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = registerRegexp) String username, @Pattern(regexp = registerRegexp) String password) {
        User u = userService.findByUserName(username);
        if (u == null) {
            userService.register(username, password);
            return Result.success();
        } else {
            return Result.error("用户名已被占用");
        }
    }

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result login(@Pattern(regexp = registerRegexp) String username, @Pattern(regexp = registerRegexp) String password) {
        User u = userService.findByUserName(username);


        if (u == null) {
            return Result.error("用户名错误");
        } else {
            if (Objects.equals(Md5Util.encrypByMd5(password), u.getPassword())) {
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", u.getId());
                claims.put("username", u.getUsername());
                String token = JwtUtil.genToken(claims);

                Map<String, Object> data = new HashMap<>();
                data.put("token", token);
                data.put("userId", u.getId());

                ValueOperations<String, String > operations = stringRedisTemplate.opsForValue();
                operations.set(token, token, 7, TimeUnit.DAYS);
                return Result.success(data);
            }
            return Result.error("密码错误");
        }
    }

//    @GetMapping("/userInfo")
//    public Result<User> userInfo(@RequestHeader(name = "Authorization") String token) {
//        Map<String, Object> claims = JwtUtil.parseToken(token);
//        Integer id = (Integer) claims.get("id");
//        User u = userService.findById(id);
//        if (u == null) {
//            return Result.error("未找到用户信息");
//        } else {
//            return Result.success(u);
//        }
//    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo() {
        Map<String, Object> map = ThreadLocalUtil.get("Authorization");
        Integer userId = (Integer) map.get("id");
        User u = userService.findById(userId);
        if (u == null) {
            return Result.error("未找到用户信息");
        } else {
            return Result.success(u);
        }
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }

    /**
     * 更新头像
     * @param avatarUrl
     * @return
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    /**
     * 更新密码
     * @param params
     * @return
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd( @RequestBody Map<String,String> params, @RequestHeader String token) {
        System.out.println(params);
        String oldPwd = params.get("oldPwd");
        String newPwd = params.get("newPwd");
        String rePwd = params.get("rePwd");
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要参数");
        }
        Map<String, Object> map = ThreadLocalUtil.get("Authorization");
        Integer userId = (Integer) map.get("id");
        User user = userService.findById(userId);

        if (!user.getPassword().equals(Md5Util.encrypByMd5(oldPwd))) {
            return Result.error("原密码输入错误");
        }
        if (!newPwd.equals(rePwd)) {
            return Result.error("两次输入的新密码不一致");
        }
        userService.updatePassword(Md5Util.encrypByMd5(newPwd));
        ValueOperations<String, String > operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }
}
